﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CSharp_Remote_Control.Enum;
using CSharp_Remote_Control.Model;
using CSharp_Remote_Control.Utils;
using Newtonsoft.Json;

namespace CSharp_Remote_Control.Pages
{
    /// <summary>
    /// Interaction logic for RCServer.xaml
    /// </summary>
    public partial class RCServer : System.Windows.Controls.UserControl
    {
        class ViewModel : INotifyPropertyChanged
        {
            string? _port = "5000";
            public string? Port
            {
                get { return _port; }
                set { _port = value; OnPropertyChanged("Port"); }
            }
            protected internal virtual void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
            public event PropertyChangedEventHandler? PropertyChanged;
        }

        class ClientItemViewModel : INotifyPropertyChanged
        {
            string? _ip = "127.0.0.1";
            public string? Ip
            {
                get { return _ip; }
                set { _ip = value; OnPropertyChanged("Ip"); }
            }

            /// <summary>
            /// 控制端端口
            /// </summary>
            int? _port = 5000;
            public int? Port
            {
                get { return _port; }
                set { _port = value; OnPropertyChanged("Port"); }
            }

            string? _deviceCode = "";
            public string? DeviceCode
            {
                get { return _deviceCode; }
                set { _deviceCode = value; OnPropertyChanged("DeviceCode"); }
            }


            string? _deviceCodeConnect = "";
            public string? DeviceCodeConnect
            {
                get { return _deviceCodeConnect; }
                set { _deviceCodeConnect = value; OnPropertyChanged("DeviceCodeConnect"); }
            }


            /// <summary>
            /// 控制端客户端
            /// </summary>
            public TcpClient? Client { get; set; }


            /// <summary>
            /// 被连接的客户端
            /// </summary>
            public ClientItemViewModel? ClientConnect { get; set; }


            protected internal virtual void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
            public event PropertyChangedEventHandler? PropertyChanged;
        }

        ViewModel? VM;
        /// <summary>
        /// 所有客户端连接
        /// </summary>
        ObservableCollection<ClientItemViewModel> ClientVMs = new ObservableCollection<ClientItemViewModel>();
        /// <summary>
        /// 当前选中的客户端连接
        /// </summary>
        ClientItemViewModel ClientVMSelected;

        public RCServer()
        {
            InitializeComponent();
            this.VM = new ViewModel();
            this.DataContext = this.VM;
            this.cbClients.ItemsSource = this.ClientVMs;
        }


        private void BtnOpenServer_Click(object sender, RoutedEventArgs e)
        {

            TCPServer s = TCPServer.getInstance();
            if (s.EnumState != Enum.EnumState.OPENED)
            {
                s.OnServerStartEvent += (int p) =>
                {
                    TxtReceive.AppendText($"服务器启动，监听端口 {p}..." + Environment.NewLine);
                };
                s.OnServerMsgJsonEvent += (string? s, TcpClient client) =>
                {
                    // 区分消息建立控制端被控端映射
                    TxtReceive.Dispatcher.BeginInvoke(() =>
                    {
                        TxtReceive.AppendText($"客户端消息: {s?.Substring(0, 100)}" + Environment.NewLine);
                        if (TxtReceive.Text.Length > 10000)
                        {
                            TxtReceive.Text = TxtReceive.Text.Substring(5000);
                        }
                    });

                    TransformModel? m = JsonConvert.DeserializeObject<TransformModel>(s);
                    if (m == null) return;
                    ClientItemViewModel? clientItemViewModelFrom;
                    ClientItemViewModel? clientItemViewModelTo;

                    switch (m.Type)
                    {
                        // 连接后配置客户端信息
                        case EnumState.TCP_CONFIG_WHEN_START:
                            cbClients.Dispatcher.BeginInvoke(() =>
                            {
                                ClientItemViewModel? clientItem = new ClientItemViewModel();

                                clientItem.Ip = m.IpFrom;
                                clientItem.DeviceCode = m.codeFrom;
                                clientItem.Port = m.PortFrom;
                                clientItem.Client = client;

                                ClientVMs.Add(clientItem);
                            });
                            break;

                        case EnumState.TCP_IMG:
                            // 接收到被控端
                            // 发送给控制端
                            // 找到要控制的客户端
                            clientItemViewModelFrom = ClientVMs.Where(x =>
                                x.DeviceCode == m.codeFrom
                            ).FirstOrDefault();
                            // 被控端
                            clientItemViewModelTo = ClientVMs.Where(x =>
                                x.DeviceCode == m.codeTo
                            ).FirstOrDefault();


                            // 发送消息让被控端传送视频数据
                            if (clientItemViewModelTo != null)
                            {
                                MsgUtil.SendMsgObj(clientItemViewModelTo.Client
                                    , new TransformModel
                                    {
                                        codeFrom = clientItemViewModelFrom.DeviceCode,
                                        codeTo = clientItemViewModelFrom.DeviceCodeConnect,
                                        pwdTo = "",
                                        DataBase64 = m.DataBase64,
                                        Type = EnumState.TCP_IMG_SERVER_FORWARD
                                    });
                            }

                            break;
                        case EnumState.TCP_TEXT:
                            // 接收到被控端
                            break;
                        case EnumState.TCP_CONFIG_CONTROL:
                            // 找到要控制的客户端
                            clientItemViewModelFrom = ClientVMs.Where(x =>
                                x.DeviceCode == m.codeFrom
                            ).FirstOrDefault();
                            // 被控端
                            clientItemViewModelTo = ClientVMs.Where(x =>
                                x.DeviceCode == m.codeTo
                            ).FirstOrDefault();
                            if (clientItemViewModelFrom != null)
                            {
                                clientItemViewModelFrom.DeviceCodeConnect = m.codeTo;
                                clientItemViewModelFrom.ClientConnect = clientItemViewModelTo;
                            }

                            // 发送消息让被控端传送视频数据
                            if (clientItemViewModelTo != null)
                            {
                                MsgUtil.SendMsgObj(clientItemViewModelTo.Client
                                    , new TransformModel
                                    {
                                        codeFrom = clientItemViewModelFrom.DeviceCode,
                                        codeTo = clientItemViewModelFrom.DeviceCodeConnect,
                                        pwdTo = "",
                                        Type = EnumState.TCP_CONFIG_CONTROL_BEGIN
                                    });
                            }
                            break;
                        default:
                            break;
                    }

                };
                // 连接成功
                s.OnClientConnectEvent += (String? ip, int? port, TcpClient client) =>
                {
                    TxtReceive.Dispatcher.BeginInvoke(() =>
                    {
                        TxtReceive.AppendText($"客户端连接: {ip}:{port}" + Environment.NewLine);

                    });
                };
                s.Open(int.Parse(this.VM.Port));
            }

        }

        private void cbClients_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.ClientVMSelected = (ClientItemViewModel)this.cbClients.SelectedItem;
        }

        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            byte[] data = Encoding.UTF8.GetBytes(TxtSend.Text);
            NetworkStream? n1 = this.ClientVMSelected?.Client?.GetStream();
            n1?.Write(data, 0, data.Length);
        }

        /// <summary>
        /// 关闭时, 销毁TCPServer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
        }
    }
}
